package com.ys.utils.yinsheng.yztdock.util;

import com.ys.utils.spring.config.SystemError;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@SuppressWarnings("deprecation")
public class HttpClientUtil {

	private static final String CHARSET = "UTF-8";
	private static final Log log = LogFactory.getLog(HttpClientUtil.class);
	
	public static String sendHttpMessage(String url,Map<String, String> map) throws Exception{
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			if(StringUtil.isEmpty(url) || null == map || map.isEmpty()){
				return null;
			}
			//创建POST请求
			HttpPost post = new HttpPost(url);
			post.setHeader("Content-type", (new StringBuilder()).append("application/x-www-form-urlencoded; charset=").append(CHARSET).toString());
	        post.setHeader("Accept",new StringBuffer("text/xml;charset=").append(CHARSET).toString());
	        post.setHeader("Cache-Control", "no-cache");
	        
	        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
	        //请求参数
			for(Entry<String,String> entry : map.entrySet()){
				params.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); 
			}
	        post.setEntity(new UrlEncodedFormEntity(params, CHARSET));
	        
			//发送请求
			client = HttpClients.createDefault();
			response = client.execute(post);
			if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
				throw new Exception("请求失败！");
			}
			
			HttpEntity resEntity = response.getEntity();
			return null == resEntity ? "" : EntityUtils.toString(resEntity,CHARSET);
		} catch (Exception e) {
			log.info("异常："+e);
			throw e;
		}finally {
			 try{
				 if(response != null){
					 response.close();
	            }
				 if(client != null){
					 client.close();
	            }
			 } catch (IOException e) {
				 log.error(e.getMessage(), e);
			 }
	        
		}
	}
	
	public static String sendHttpMessage(String url,Map<String, String> map, File file,String fileKey) throws Exception{
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		HttpPost post = null;
		try {
			if(StringUtil.isEmpty(url) || null == map || map.isEmpty()){
				return null;
			}
			//创建POST请求
			post = new HttpPost(url);
			post.setHeader("Server","nginx/1.14.2");
	        MultipartEntity entity = new MultipartEntity();  
	        //请求参数
			for(Entry<String,String> entry : map.entrySet()){
//				params.add(new BasicNameValuePair(key,map.get(key))); 
				entity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName("UTF-8")));  
			}
		    entity.addPart(fileKey,new FileBody(file));  
		    post.setEntity(entity);  
			//发送请求
			 client = HttpClients.createDefault();
			 response = client.execute(post);
			if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
				throw new Exception("请求失败！");
			}
			
			HttpEntity resEntity = response.getEntity();
			return null == resEntity ? "" : EntityUtils.toString(resEntity,CHARSET);
		}  catch (Exception e) {
			log.info("异常："+e);
			throw e;
		}
	finally {
		 try{
			 if(response != null){
				 response.close();
            }
			 if(client != null){
				 client.close();
            }
			 if (post != null) {
				post.releaseConnection();
			}
		 } catch (IOException e) {
			 log.error(e.getMessage(), e);
		 }
        
	}
	}
	
		/**
	     * @功能描述：httpclient发送json请求
	     * @param url
	     * @param json
	     * @return  
	     */
		public static String sendJson(String url,JSONObject json){
	    	log.info("====================================发送【开始】============================================"); 
	    	log.info("请求数据：url="+url+";json数据：" + json.toString()); 
    	    long startTime = 0L;
    	    long endTime = 0L; 
    	    int statusCode = 0; 
    	    CloseableHttpClient client = null;
    	    CloseableHttpResponse response = null;
	        HttpPost post = new HttpPost(url);
//	        post.setHeader("Server","nginx/1.14.2");
	        
	        
	        String body = null;
	        try {   
	            StringEntity s = new StringEntity(json.toString(), HTTP.UTF_8);   
	            s.setContentType("application/json");
	            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
	            post.setEntity(s);   
	            //开始时间
	            startTime = System.currentTimeMillis(); 
	            client = HttpClients.createDefault();
	            response = client.execute(post);   
	            //结束时间
	            endTime = System.currentTimeMillis(); 
	            log.info("调用花费时间(单位：毫秒)：" + (endTime - startTime)); 
	            statusCode = response.getStatusLine().getStatusCode(); 
	            log.info("HttpStatusCode:" + statusCode); 
	            if(statusCode == org.springframework.http.HttpStatus.OK.value()){   
	                body=EntityUtils.toString(response.getEntity());  
	            }else{
					SystemError.wrapBs("500","调用失败,状态码HttpStatusCode="+statusCode);
	            }
	        }catch(Throwable e){   
	        	log.error(e.getMessage(),e);
                 SystemError.wrapBs("500","通讯连接异常,状态码HttpStatusCode="+statusCode);
	        }finally{ 
	        	try{
	   			 if(response != null){
	   				 response.close();
	               }
	   			 if(client != null){
	   				 client.close();
	               }
	   			 if (post != null) {
	   				post.releaseConnection();
	   			}
	   		 } catch (IOException e) {
	   			 log.error(e.getMessage(), e);
	   		 }
	        	log.info("调用接口状态码：" + statusCode); 
            } 
	        log.info("回执数据：" + body); 
	        log.info("====================================发送【结束】============================================"); 
	        return body;   
	   }
}
